package logic

import (
	"context"
	"encoding/json"
	"time"

	"googee/common/errorx"
	"googee/common/utils"
	"googee/service/user/api/internal/svc"
	"googee/service/user/api/internal/types"
	"googee/service/user/rpc/user"

	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type RefreshjwtLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRefreshjwtLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RefreshjwtLogic {
	return &RefreshjwtLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RefreshjwtLogic) Refreshjwt() (resp *types.RefreshJWTReply, err error) {
	resp = &types.RefreshJWTReply{}

	id, err := l.ctx.Value("userId").(json.Number).Int64()
	if err != nil {
		return nil, err
	}
	u, err := l.svcCtx.User.GetUser(l.ctx, &user.IdRequest{Id: id})

	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			if st.Code() == codes.NotFound {
				return nil, errorx.NewCodeErrorNoMsg(errorx.USER_ERROR + 1)
			} else if st.Code() == codes.Internal {
				return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "系统内部未知错误")
			}
		} else {
			return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "系统内部未知错误")
		}
	}

	if u.Isderegister == 1 {
		return nil, errorx.NewCodeErrorNoMsg(errorx.USER_ERROR + 7)
	}

	now := time.Now().Unix()
	accessExpire := l.svcCtx.Config.Auth.AccessExpire

	jwt, _ := utils.GetJwtToken(l.svcCtx.Config.Auth.AccessSecret, now, accessExpire, u.Id)
	resp.Data.AccessExpire = now + accessExpire
	resp.Data.RefreshAfter = now + accessExpire/2
	resp.Data.AccessToken = jwt
	return resp, nil
}
